package code.db.executor;

import java.util.List;

import code.db.DBExecutor;
import code.db.mapper.ColumnRowMapper;
import code.db.mapper.TableRowMapper;
import code.domain.Column;
import code.domain.Table;

public class MySQLExecutor extends DefaultDBExecutor implements DBExecutor {

	private final String getTableSQL = "select table_name, table_comment as comments "
			+ "from information_schema.TABLES "
			+ "where TABLE_SCHEMA= database() and TABLE_NAME= ?"; 
	private final String getColumnSQL = "SELECT "
			 + "column_name, "
			 + "COLUMN_COMMENT COMMENTS, "
			 + "DATA_TYPE, "
			 + "IS_NULLABLE NULLABLE, "
			 + "COLUMN_DEFAULT DATA_DEFAULT "
			 + "FROM "
			 + "information_schema.COLUMNS "
			 + "WHERE "
			 + "TABLE_SCHEMA = database() "
			 + "AND TABLE_NAME = ? ";
	
	public Table getTable(String tableName){
		Table table = (Table) dbTemplate.queryForObject(getTableSQL, new String[]{tableName}, new TableRowMapper());
		if(table != null){
			List<Column> columnList = getColumns(tableName);
			table.setColumnList(columnList);
		}
		return table;
	}
	
	public List<Column> getColumns(String tableName){
		List<Column> columnList = dbTemplate.query(getColumnSQL, new String[]{tableName}, new ColumnRowMapper());
		return columnList;
	}
}
